//package com.xjscrm.console.chat.dispatch;
//
//import com.alibaba.fastjson.JSON;
//import com.uzai.mobile.collect.api.dto.trigger.talk.MicaTalkContentTextMsg;
//import com.xjscrm.console.chat.cache.CacheHolder;
//import com.xjscrm.console.chat.dispatch.match.AllocateRule;
//import com.xjscrm.console.chat.dispatch.match.DispatchCondition;
//import com.xjscrm.console.chat.utils.MessageUtil;
//import com.xjscrm.console.entity.ChatSettings;
//import com.xjscrm.console.entity.ChatTalkRecord;
//import com.xjscrm.console.entity.ChatTalkSession;
//import com.xjscrm.console.entity.ChatTalkSessionStaffRel;
//import com.xjscrm.console.service.customer.chat.ChatSettingsService;
//import com.xjscrm.console.service.customer.chat.ChatDispatchSettingsService;
//import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
//import com.xjscrm.console.service.customer.chat.ChatTalkSessionStaffRelService;
//import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
//import com.xjscrm.console.vo.chat.ChatDispatchSettingsVO;
//import io.netty.channel.Channel;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.List;
//import java.util.Objects;
//
///**
// * @author mingyang.chen create in 2024/3/12 18:35
// */
//@Component
//@Slf4j
//public class MsgDispatcher {
//
//    @Autowired
//    private CacheHolder cacheHolder;
//
//    @Autowired
//    private DispatchCondition keywordsDispatchCondition;
//    @Autowired
//    private AllocateRule staffAllocateRule;
//    @Autowired
//    private ChatDispatchSettingsService dispatchSettingsService;
//    @Autowired
//    private ChatTalkSessionStaffRelService chatTalkSessionStaffRelService;
//    @Autowired
//    private ChatSettingsService chatSettingsService;
//    @Autowired
//    private ChatTalkSessionService chatTalkSessionService;
//    @Autowired
//    private WwDeviceService wwDeviceService;
//
////    protected ChatTalkSession build(WwDevice device, MicaFriendTalkMsg micaFriendTalkMsg) {
////        ChatTalkSession newTalkSession = new ChatTalkSession();
////
////        newTalkSession.setId(IdUtil.getSnowflakeNextId());
////        newTalkSession.setMerId(device.getMerId());
////        newTalkSession.setDeviceId(device.getDeviceId());
////        newTalkSession.setDeviceType(device.getDeviceType());
////        newTalkSession.setDeviceUniqueId(device.getId());
////        newTalkSession.setConversationId(micaFriendTalkMsg.getConversationId());
////        newTalkSession.setConversationName(micaFriendTalkMsg.getConversationName());
////        newTalkSession.setType(micaFriendTalkMsg.getGroup() ? 111 : 110);
////        newTalkSession.setLastTalkTime(micaFriendTalkMsg.getSendTime().intValue());
////
////        newTalkSession.setOpenShield(0);
////
////        newTalkSession.setCreateTime((int) (System.currentTimeMillis() / 1000L));
////
////        return newTalkSession;
////    }
////
////    protected ChatTalkRecord build(MicaFriendTalkMsg micaFriendTalkMsg, ChatTalkSession session) {
////        ChatTalkRecord chatTalkRecord = new ChatTalkRecord();
////
////        chatTalkRecord.setMerId(session.getMerId());
////        chatTalkRecord.setTalkSessionId(session.getId());
////        chatTalkRecord.setDeviceUniqueId(session.getDeviceUniqueId());
////        chatTalkRecord.setConversationId(session.getConversationId());
////        chatTalkRecord.setSendWxId(micaFriendTalkMsg.getSendWxId());
////        chatTalkRecord.setContentType(micaFriendTalkMsg.getMsgType());
////
////        chatTalkRecord.setContent(micaFriendTalkMsg.getJsonContent());
////        chatTalkRecord.setSendTime(micaFriendTalkMsg.getSendTime().intValue());
////        chatTalkRecord.setWxSendTime(micaFriendTalkMsg.getSendTime().intValue());
////        chatTalkRecord.setSendStatus(ChatTalkRecordSendStatus.send_success.getCode());
////        chatTalkRecord.setRemoteMsgId(micaFriendTalkMsg.getRemoteMsgId());
////        chatTalkRecord.setMsgId(micaFriendTalkMsg.getMsgId());
////        chatTalkRecord.setCreateTime((int) (System.currentTimeMillis() / 1000L));
////
////        return chatTalkRecord;
////    }
//
////    public void dispatch(Long merId, String deviceId, MicaFriendTalkMsg micaFriendTalkMsg, Consumer<Long> routeMsg) {
////
////        String convId = micaFriendTalkMsg.getConversationId();
////
////        // 1. 根据设备Id查询到设备信息, 判断其设备
////        WwDevice device = wwDeviceService.getByDeviceId(merId, deviceId);
////        if (Objects.isNull(device)) {
////            log.error("消息分发失败, 设备未找到. 运营商: {}, 设备id: {}", merId, deviceId);
////            return;
////        }
////        Long deviceUniqueId = device.getId();
////
////        // 2. 查询此会话是否关联员工
////        ChatTalkSessionStaffRel sessionStaffRel = chatTalkSessionStaffRelService.getBySessionId(merId, deviceUniqueId, convId);
////
////        Long staffId;
////        boolean addRecord = false;
////        boolean addSession = false;
////        ChatTalkRecord record;
////        ChatTalkSession session = null;
////        //
////        if (Objects.nonNull(sessionStaffRel)) {
////            if (Objects.equals(sessionStaffRel.getEnd(), 1)) {
////                log.error("消息分发失败, 当前会话已结束.");
////                return;
////            }
////            if (Objects.equals(sessionStaffRel.getOpenShield(), 1)) {
////                log.error("消息分发失败, 当前会话已屏蔽.");
////                return;
////            }
////            staffId = sessionStaffRel.getStaffId();
//////            Channel staffChannel = cacheHolder.getStaffChannel(staffId);
//////            if (Objects.isNull(staffChannel)) {
//////                log.error("消息分发失败, 员工未上线. 路由消息: {}", staffId);
//////                routeMsg.accept(staffId);
//////                return;
//////            }
////            Long talkSessionId = sessionStaffRel.getTalkSessionId();
////            session = chatTalkSessionService.getById(merId, talkSessionId);
////            addRecord = true;
////        }
////        //
////        else {
////            addSession = true;
////            //
////            ChatDispatchSettingsVO dispatchSettings = dispatchSettingsService.get(merId);
////            staffId = staffAllocateRule.allocateStaffId(merId, deviceUniqueId, dispatchSettings.getAllocateRuleConf());
////            if (Objects.isNull(staffId)) {
////                log.error("消息分发未找到合适的员工, 进入排队等待");
////                cacheHolder.enqueueSession(merId, deviceUniqueId, id);
////                return;
////            }
////
////            boolean increment = false;
////            try {
////                //
////                Integer staffLimitCount = cacheHolder.getStaffSessionCount(merId, staffId);
////                //
////                Integer staffSessionNowCount = cacheHolder.incrementStaffSessionNowCount(merId, staffId);
////                if (Objects.nonNull(staffSessionNowCount)) {
////                    increment = true;
////                }
////                //
////                if (Objects.nonNull(staffSessionNowCount) && staffSessionNowCount > staffLimitCount) {
////                    log.info("消息分发失败, 员工回话数上限");
////                    cacheHolder.enqueueSession(merId, deviceUniqueId, id);
////                    return;
////                }
////                //
////                chatTalkSessionStaffRelService.addIfAbsent(merId, talkSession, staffId);
////                //
////                cacheHolder.setSessionOrder(merId, deviceUniqueId, id);
////            } catch (Exception e) {
////                if (increment) {
////                    cacheHolder.decrementStaffSessionNowCount(merId, staffId);
////                }
////                throw e;
////            }
////        }
////
////        if (addSession) {
////            session = this.build(device, micaFriendTalkMsg);
////        }
////        //
////        if (addRecord && Objects.nonNull(session)) {
////            record = this.build(micaFriendTalkMsg, session);
////        }
////    }
//
//    // 分发回话和聊天
//    @Transactional
//    public void dispatch(ChatTalkSession talkSession, ChatTalkRecord chatTalkRecord) {
//
//        Long merId = talkSession.getMerId();
//        Long deviceUniqueId = talkSession.getDeviceUniqueId();
//        Long id = talkSession.getId();
//        // 1. 判断当前回话是否已经关联员工, 如果关联员工,直接分发
//
//        if (Objects.equals(chatTalkRecord.getContentType(), 1)) {
//            MicaTalkContentTextMsg textMsg = JSON.parseObject(chatTalkRecord.getContent(), MicaTalkContentTextMsg.class);
//            String text = textMsg.getText();
//
//            ChatSettings chatSettings = chatSettingsService.selectByMerId(merId);
//            if (Objects.nonNull(chatSettings) && Objects.equals(chatSettings.getOpenKeywordShield(), 1)) {
//
//                String blurKeyword = chatSettings.getBlurKeyword();
//                String exactKeyword = chatSettings.getExactKeyword();
//
//                if (StringUtils.isNotEmpty(blurKeyword)) {
//                    List<String> blurKeywords = JSON.parseArray(blurKeyword, String.class);
//                    if (blurKeywords.stream().anyMatch(item -> StringUtils.containsAny(text, item))) {
//                        log.error("分发消息失败, 匹配到了模糊关键词");
//                        return;
//                    }
//                }
//                if (StringUtils.isNotEmpty(exactKeyword)) {
//                    List<String> exactKeywords = JSON.parseArray(exactKeyword, String.class);
//                    if (exactKeywords.stream().anyMatch(item -> StringUtils.equals(text, item))) {
//                        log.error("分发消息失败, 匹配到了精准关键词");
//                        return;
//                    }
//                }
//            }
//        }
//
//        // 2. 会话未关联员工,则走分发流程
//        // 2.1: 如果不是文本消息则走下一个步骤
//        // 2.2: 文本消息匹配关键词
//        Long staffId;
//        ChatTalkSessionStaffRel byConversationId = chatTalkSessionStaffRelService.getBySessionId(merId, talkSession.getDeviceUniqueId(), talkSession.getConversationId());
//        if (Objects.nonNull(byConversationId)) {
//            if (Objects.equals(1, byConversationId.getEnd())) {
//                log.error("分发消息失败, 当前会话已结束.");
//                return;
//            }
//            if (Objects.equals(1, byConversationId.getOpenShield())) {
//                log.error("分发消息失败, 当前会话已被屏蔽.");
//                return;
//            }
//            staffId = byConversationId.getStaffId();
//            cacheHolder.setSessionOrder(merId, deviceUniqueId, id);
//        } else {
//            // 3.
//            ChatDispatchSettingsVO dispatchSettingsVO = dispatchSettingsService.get(merId);
//
//            if (Objects.equals(chatTalkRecord.getContentType(), 1)) {
//                MicaTalkContentTextMsg textMsg = JSON.parseObject(chatTalkRecord.getContent(), MicaTalkContentTextMsg.class);
//                String text = textMsg.getText();
//                Boolean match = keywordsDispatchCondition.match(text, dispatchSettingsVO.getDispatchConditionConf());
//                if (!match) {
//                    log.error("分发消息失败, 未通过关键词过滤: {}", text);
//                    return;
//                }
//            }
////        if (cacheHolder.delSessionOrder(merId, deviceUniqueId, id)) {
////            log.info("消息分发未完成, 当前回话已在队列中排队");
////            return;
////        }
//            staffId = staffAllocateRule.allocateStaffId(merId, deviceUniqueId, dispatchSettingsVO.getAllocateRuleConf());
//            if (Objects.isNull(staffId)) {
//                log.info("消息分发未找到合适的员工, 进入排队等待");
//                cacheHolder.enqueueSession(merId, deviceUniqueId, id);
//                return;
//            }
//
//            List<Long> deviceStaffs = cacheHolder.getDeviceStaffs(deviceUniqueId);
//            if (!deviceStaffs.contains(staffId)) {
//                log.error("员工未关联机器人, 此消息将停止分发");
//                return;
//            }
//
//            boolean increment = false;
//            try {
//                //
//                Integer staffLimitCount = cacheHolder.getStaffSessionCount(merId, staffId);
//                //
//                Integer staffSessionNowCount = cacheHolder.incrementStaffSessionNowCount(merId, staffId);
//                if (Objects.nonNull(staffSessionNowCount)) {
//                    increment = true;
//                }
//                //
//                if (Objects.nonNull(staffSessionNowCount) && staffSessionNowCount > staffLimitCount) {
//                    log.info("消息分发失败, 员工回话数上限");
//                    cacheHolder.enqueueSession(merId, deviceUniqueId, id);
//                    return;
//                }
//                //
//                chatTalkSessionStaffRelService.addIfAbsent(merId, talkSession, staffId);
//                //
//                cacheHolder.setSessionOrder(merId, deviceUniqueId, id);
//            } catch (Exception e) {
//                if (increment) {
//                    cacheHolder.decrementStaffSessionNowCount(merId, staffId);
//                }
//                throw e;
//            }
//        }
//
//        Channel staffChannel = cacheHolder.getStaffChannel(staffId);
//        if (Objects.isNull(staffChannel)) {
//            log.error("消息分发的员工未上线, 忽略消息");
//            return;
//        }
//        //
//        chatTalkSessionService.addChatSendDelayTask(merId, staffId, talkSession);
//        //
//        MessageUtil.sendNewSessionTalk(staffChannel, talkSession, chatTalkRecord);
//    }
//}
